package com.dlkw.easyroom.sample;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.dlkw.easyroom.EasyRoom;
import com.dlkw.easyroom.InitInterceptor;

import java.util.List;
import java.util.function.Function;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        EasyRoom.init(this, "user.db", new InitInterceptor() {
            @Override
            public void intercept(RoomDatabase.Builder<? extends RoomDatabase> builder) {
                builder.allowMainThreadQueries();
                builder.addMigrations(new Migration(1, 2) {
                    @Override
                    public void migrate(@NonNull SupportSQLiteDatabase database) {
                        database.execSQL("CREATE TEMPORARY TABLE temp_table AS SELECT * FROM User;");
                        database.execSQL("CREATE TABLE IF NOT EXISTS `User222` (`id` TEXT NOT NULL, PRIMARY KEY(`id`))");
                        database.execSQL("INSERT INTO User222 SELECT * FROM temp_table;");
                        database.execSQL("CREATE VIEW `UserView111` AS SELECT * FROM User222");
                    }
                });
            }
        });
        UserDao userDao = EasyRoom.getDao(UserDao.class);
        User user = new User();
        user.setId(String.valueOf(System.currentTimeMillis()));
        userDao.insert(user);

        List<User> users = userDao.listAll();

        System.out.println("userDao=" + userDao);
        System.out.println("userDao.count1=" + userDao.execute("select count(*) from user222", Integer.class));
        System.out.println("userDao.count2=" + userDao.count());

        test(User::getId, user);
    }

    private <T, R> R test(Function<T, R> function, T t) {
        System.out.println("function=" + function);
        return function.apply(t);
    }
}